{% extends 'layout/layui_base_page.html' %}
{% load static %}

<!-- Title -->
{% block title %} 角色管理 {% endblock %}

<!-- CSS -->
{% block css %} {% endblock %}

<!-- Content -->
{% block content %}
    <!-- 内容01: 面包屑导航 -->
    <span class="layui-breadcrumb">
      <a href="javascript:;">首页</a>
      <a href="javascript:;">用户角色</a>
      <a><b>角色管理</b></a>
    </span>

    <!-- 内容02: 查询区域 --->
    <div id="queryArea" style="margin-top: 20px;">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="q_str"><b>查询条件：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="q_str" id="q_str" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" id="btnQuery" class="layui-btn" style="width: 100px"><i
                            class="fa fa-search"></i>&nbsp;&nbsp;查询
                    </button>
                    <button type="button" id="btnAll" class="layui-btn" style="width: 100px"><i class="fa fa-list"></i>&nbsp;&nbsp;全部
                    </button>
                    <button type="button" id="btnAdd" class="layui-btn" style="width: 100px"><i
                            class="fa fa-plus-circle"></i>&nbsp;&nbsp;添加
                    </button>
                </div>
            </div>
        </form>

    </div>

    <!-- 内容03: 表格部分 -->
    <table class="layui-hide" id="tableArea" lay-filter="tableArea"></table>

    <!-- 内容04：表格右侧的操作按钮 -->
    <script type="text/html" id="tableButton">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">
            <i class="fa fa-edit" aria-label="true"></i>&nbsp;编辑
        </a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">
            <i class="fa fa-trash" aria-label="true"></i>&nbsp;删除
        </a>
        <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="permission">
            <i class="fa fa-key" aria-label="true"></i>&nbsp;分配权限
        </a>
    </script>

    <!-- 内容05：添加和修改的弹出层 -->
    <div id="layerArea" style="display: none; padding: 30px;">
        <form id="layerForm" class="layui-form" lay-filter="layerForm">
            {% csrf_token %}

            <div class="layui-form-item">
                <div class="layui-inline" style="display: none">
                    <label class="layui-form-label" for="id"><b> 编号：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="id" id="id" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="name"><b> 角色名称：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" id="name" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>

            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="desc"><b> 角色描述：</b></label>
                    <div class="layui-input-inline">
                        <textarea type="text" id="desc" name="desc" class="layui-textarea"></textarea>
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="create_time"><b> 创建时间：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" id="create_time" name="create_time" class="layui-input"
                               style="background-color:#eaeaea">
                    </div>
                </div>

            </div>
            <div class="layui-form-item">

                <div class="layui-inline">
                    <label class="layui-form-label" for="edit_time"><b> 修改时间：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" id="edit_time" name="edit_time" class="layui-input"
                               style="background-color:#eaeaea">
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- 内容06：分配权限的弹出层 -->
    <div id="permissionArea" class="demo-tree demo-tree-box" style="padding: 20px; display: none"></div>
{% endblock %}

<!-- JS -->
{% block js %}
    <script>
        let Operation = 0;  // 1-- 添加  2--修改

        // 定义全局变量存储初始化树状结构
        let AllPermission = "";
        // 入口函数
        $(function () {
            // === 初始化页面 ===
            //initPage();
            // === 初始化表格 ===
            initTable();
            // === 按钮点击 ===
            buttonClick();

        });


        // ============ 初始化表格的功能实现 ================
        function initTable() {
            layui.use(['table', 'form'], function () {
                let table = layui.table;
                let form = layui.form;

                // ===渲染表格===
                table.render({
                    elem: $('#tableArea')
                    , url: "{% url 'list_roles' %}"
                    , method: 'post'
                    , where: {
                        // 携带输入的查询条件！
                        q_str: $('#q_str').val().trim(),
                        // q_experiment: $('#q_experiment').val().trim(),
                        csrfmiddlewaretoken: "{{ csrf_token }}",
                    }
                    , even: true
                    , cols: [[
                        {type: 'numbers', width: 60, title: '序号', align: 'center', sort: true}
                        , {field: 'name', width: 200, title: '角色名称', align: 'center', sort: true}
                        , {field: 'desc', title: '角色描述', align: 'center',}
                        , {fixed: 'right', title: '操作', width: 260, align: 'center', toolbar: '#tableButton'}
                    ]]
                    , page: true  // 启用分页，默认就向后台发送两个参数：page=1,limit=10
                    , limit: 15
                    , limits: [12, 15, 18, 20, 30, 50, 75, 100]
                    , done: function (res, current, count) {
                        $('thead tr').css({'background-color': '#009688', 'color': 'white'})
                    }

                });

                // ===侦听表格的按钮点击===
                table.on('tool(tableArea)', function (obj) {
                    // 取出当前行数据
                    let oneLineData = obj.data;
                    // 响应按钮的点击事件
                    if (obj.event === 'edit') {
                        // 修改Operation
                        Operation = 2;
                        // 点击编辑按钮的代码
                        loadLayer("修改【角色信息】", oneLineData);

                    } else if (obj.event === 'del') {
                        // 点击删除按钮的代码
                        deleteValue(oneLineData);

                    } else if (obj.event === 'permission') {

                        loadPermissionLayer(oneLineData);
                    }
                })
            })

        }

        // ============ 按钮点击的实现  ====================
        function buttonClick() {
            // === 添加按钮 ===
            $('#btnQuery').on('click', function () {
                initTable();
            });
            // === 显示全部 ===
            $('#btnAll').on('click', function () {
                location.reload();
            });
            // === 添加 ===
            $('#btnAdd').on('click', function () {
                // 修改Operation的值
                Operation = 1;
                loadLayer("添加【角色信息】");
            });
        }

        // ============ 展示弹出层 =========================
        function loadLayer(title, value = "") {

            // 展示弹出层的内容
            layui.use(['layer', 'form'], function () {
                let layer = layui.layer;
                let form = layui.form;

                layer.open({
                    type: 1,
                    title: "<b style='color:navy'>" + title + "</b>",
                    area: ['400px', '500px'],
                    offset: '30px',
                    btn: ['确定', '取消'],
                    content: $('#layerArea'),
                    resize: false,

                    // ===================== 三个回调函数 =====================
                    success: function (index, layero) {
                        // === 为非下拉框赋值 ====
                        form.val('layerForm', value);
                        form.render();

                        // 创建日期和修改日期只读
                        $('#layerForm').find('#create_time, #edit_time').prop('readonly', true);
                    },
                    yes: function (index, layero) {

                        // 清除表单的错误提示
                        $('.error_msg').empty();
                        // 表单的验证
                        if (!checkLayerForm()) {
                            return;
                        }
                        // 准备提交的URL
                        let commitURL = "{% url 'add_roles' %}";
                        if (Operation === 2) {
                            commitURL = "{% url 'edit_roles' %}";
                        }
                        // 使用Ajax提交
                        $.ajax({
                            url: commitURL,
                            method: 'post',
                            data: $('#layerForm').serialize(),
                            dataType: 'json',
                            success: function (res) {
                                if (res.status) {
                                    location.reload();
                                } else {
                                    layer.msg(res.error, {
                                        icon: 2,
                                        area: ['300px', '150px'],
                                        time: -1,
                                        btn: ['关闭']
                                    })
                                }
                            }
                        })
                    },
                    end: function (index, layero) {
                        // ==== 清空所有的表单值 ===
                        form.val('layerForm', {
                            id: "",
                            name: "",
                            desc: "",
                            create_time: "",
                            edit_time: "",
                        });

                        // 清除表单的错误提示
                        $('.error_msg').empty();
                    },

                })
            })
        }

        // =========== 分配权限的弹出层 ======================
        function loadPermissionLayer(value) {
            layui.use(['layer', 'form', 'tree'], function () {
                let layer = layui.layer;

                let tree = layui.tree;

                //展示
                layer.open({
                    type: 1,
                    title: "<b style='color:navy'>【分配权限】</b>",
                    area: ['400px', '500px'],
                    offset: '100px',
                    btn: ['确定', '取消'],
                    content: $('#permissionArea'),
                    resize: false
                    //  ========== 回调函数=============
                    , success: function (index, layero) {
                        // 获取权限的数据
                        // ==== 请求树状结构的数据====
                        $.ajax({
                            url: "{% url 'list_permission' %}"
                            , method: 'get'
                            , dataType: 'json'
                            , async: false
                            , success: function (res) {
                                // 把当前树状结构赋值给AllPermission
                                AllPermission = res.data;

                            }
                        });

                        //====== 获取当前的角色具备的权限 ============
                        $.ajax({
                            url: "{% url 'role_list_permission' %}"
                            , method: 'post'
                            , data: {
                                role_id: value.id,
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                // 获取当前角色的初始权限
                                let initPermission = res.data;
                                // ============ 修改AllPermission中选中的状态 =========
                                $.each(AllPermission, (index, value) => {
                                    //遍历权限条目
                                    $.each(value.children, (i, v) => {
                                        // 判断是否拥有这个权限
                                        if(initPermission.indexOf(v.id) != -1){
                                            v.checked = true
                                        }
                                    })
                                });
                                // 展示树状结构
                                loadTreePermission(AllPermission);

                            }
                        })


                    }
                    , yes: function (index, layero) {

                        // 定义集合
                        let commitPermission = tree.getChecked('demoid');
                        // 定义集合
                        let commitList = [];
                        // 遍历获取具体的id
                        $.each(commitPermission, (index, value)=>{
                           // 获取具体的条目
                           $.each(value.children, (i,v)=>{
                               commitList.push(v.id)
                           })
                        });

                        // 更新到数据库
                        $.ajax({
                            url:  "{% url 'role_update_permission' %}"
                            , method: 'post'
                            , data: {
                                role_id: value.id,
                                commit: JSON.stringify(commitList),
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                if (res.status) {
                                    layui.layer.msg("权限更新成功！");
                                    layer.close(index);
                                } else {
                                    layui.layer.msg(res.error, {
                                        icon: 2, btn: ['关闭'], area: ['450px', '200px'], time: -1
                                    })
                                }
                            }
                        })

                    }
                })
            })
        }


        // =============== 把权限的数据用树状结构展示 ===============
        function loadTreePermission(data) {
            layui.use(['tree', 'form'], function () {
                let tree = layui.tree;

                tree.render({
                    elem: "#permissionArea"
                    , showCheckbox: true
                    , data: data
                    , spread: false
                    , isJump: true
                    , id: 'demoid'

                })
            })
        }


        // ============= 对弹出层表单进行校验 =====================
        function checkLayerForm() {
            // 清除所有的错误
            $('.error_msg').empty();
            // 定义返回值
            let result = true;
            // 判断合同信息是否选择
            if ($('#name').val().trim().length === 0) {
                result = false;
                $('#name').next().text("角色名称不能为空！");
            }

            // 判断角色名称是否存在
            if (Operation === 1) {
                $.ajax({
                    //url: "url 'role_exists_name' %}", //判断role是否存在
                    url: "",
                    method: 'post',
                    data: {
                        name: $('#name').val().trim(),
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    },
                    dataType: 'json',
                    async: false,
                    success: function (res) {
                        if (res.status) {
                            result = false;
                            $('#name').next().text("角色名称已存在！");
                        }
                    }
                });
            }


            return result

        }


        //============= 删除计划信息 =========================
        function deleteValue(value) {
            console.log(value);
            //确认的提示
            let confirmStr = "您确认删除角色信息【" + value.name + "】信息吗？";
            // 确认
            layui.use('layer', function () {
                layer.confirm(confirmStr, {icon: 3, area: ['450px', '200px']}, function (index) {
                    // ajax
                    $.ajax({
                        url: "{% url 'del_roles' %}",
                        method: "post",
                        data: {
                            id: value.id,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        },
                        dataType: 'json',
                        success: function (res) {
                            if (res.status) {
                                location.reload();
                            } else {
                                layer.msg(res.error, {
                                    icon: 2,
                                    area: ['500px', '250px'],
                                    time: -1,
                                    btn: ['关闭']
                                });
                            }
                        }
                    })
                })
            })
        }


    </script>
{% endblock %}
